package com.tn.dao;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;

import com.newatlanta.commons.vfs.provider.gae.GaeVFS;
import com.tn.bo.Attachment;

public class GAEFileSystemDAO {

	/**
	 * Method to store file/attachments in VFS.
	 * 
	 * @param description
	 *            the description about the attachment. In case of PO, it should
	 *            be PO Number.
	 * @param theBytes
	 *            the data to be stored as byte[]
	 * @param uniqueName
	 *            Unique name for the file.
	 * @throws FileSystemException
	 * @throws IOException
	 */
	public static void storeFileInVFS(String description, byte[] theBytes,
			String uniqueName) throws FileSystemException, IOException {
		FileObject fileObject = GaeVFS.resolveFile("gae://" + uniqueName);

		OutputStream outputStream = fileObject.getContent().getOutputStream();
		
		InputStream bin = new ByteArrayInputStream(theBytes);
		IOUtils.copy(bin, outputStream);
		outputStream.flush();
		outputStream.close();
		bin.close();
		
		// Insert Attachment entry in DB
		Attachment a = new Attachment();
		a.setUniqueName(uniqueName);
		a.setDescription(description);
		a = new AttachmentDAO().insert(a);
	}
}
